package com.lingjtx.im.core.distribute;

import com.lingjtx.common.core.constant.MqConst;
import com.lingjtx.im.core.common.ChannelPool;
import com.lingjtx.im.core.handle.ImMessageHandle;
import com.lingjtx.im.core.protocol.MessageProto;
import com.lingjtx.im.core.protocol.ProtocolWrapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class MessageConsumer {

    private final MessageTypeContextWrapper contextWrapper;

    public MessageConsumer(MessageTypeContextWrapper contextWrapper) {
        this.contextWrapper = contextWrapper;
    }

    /**
     * IM 核心消息消费处理（包含各种消息类型：私聊的离线落库处理，，群聊，客服和系统通知）
     */
    @RabbitListener(queues = MqConst.IM_QUEUE_MAIN)
    public void onMainQueueMessage(ProtocolWrapper wrapper) {
        // 私聊的落库、离线推送，群聊、客服等处理
        ImMessageHandle handle = contextWrapper.getHandle(wrapper.getImType());
        handle.process(wrapper.getMessage(), wrapper.getVersion());
    }

    /**
     * 向用户所在的目标服务节点，websocket 获取 Channel 建立通信消息
     */
    @RabbitListener(queues = "#{@dynamicImQueue}")
    public void onMessage(MessageProto.IMMessage message) {
        // 此时肯定是属于当前 node 的连接，直接推送
        ChannelPool.sendToUser(message.getReceiverId(), message);
    }
}
